package com.lzx.iteam.engine;

import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import com.google.zxing.BarcodeFormat;
import com.lzx.iteam.R;
import com.lzx.iteam.bean.ContactInfo;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.dimensioncode.Contents;
import com.lzx.iteam.dimensioncode.Intents;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.ContactsUtils;
import com.lzx.iteam.util.PhoneNumberArea;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.RoundProgressBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hfx_lk on 15-1-15.
 */
public class GetContactInfo {

    private Context mContext;
    private HashMap<String, String> map_phoneNumbers, map_emails, map_address, map_iMs;
    private ArrayList<String> array_websites, array_nickName, array_notes, companys, positions;
    private String mName;
    private long mWxChatId = -1;
    private long mWxFriendId = -1;
    private StringBuilder groupString;
    private Uri mRowPhoneLookUpUri;
    private ArrayList<String> mPhoneNumbers;
    private Intent mDataIntent;

    public GetContactInfo(Context context) {
        mContext = context;
    }

    public void clearArrays(){
        if(mPhoneNumbers != null){
            mPhoneNumbers = new ArrayList<String>();
        }

        if(map_phoneNumbers != null){
            map_phoneNumbers.clear();
        }

        if(map_emails != null){
            map_emails.clear();
        }

        if(map_address != null){
            map_address.clear();
        }

        if(map_iMs != null){
            map_iMs.clear();
        }

        if(array_websites != null){
            array_websites.clear();
        }

        if(array_nickName != null){
            array_nickName.clear();
        }

        if(array_notes != null){
            array_notes.clear();
        }

        if(companys != null){
            companys.clear();
        }

        if(positions != null){
            positions.clear();
        }

        if(groupString != null){
            groupString = new StringBuilder();
        }
    }

    public ContactInfo getInfo(long contactId) throws IllegalArgumentException {
        clearArrays();
        Uri methodUri = getMethodUri(getContactUri(contactId));
        Cursor cursor = null;
        try {
            cursor = mContext.getContentResolver().query(methodUri,
                    ContactsDBReader.DATA_PROJECTION, null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                ContactInfo info = new ContactInfo();
                long rowId = getRowId(contactId);
                boolean isTrue = cursor.moveToFirst();
                mDataIntent = new Intent();
                Bundle bundle = new Bundle();
                int foundPhone = 0;
                int foundPhoneType = 0;
                int foundEmail = 0;
                int foundEmailType = 0;
                bundle.putLong("contactId", contactId);
                while (isTrue) {
                    String mime = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
                    if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(mime)) {
                        int type = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                        String label = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
                        final String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        String numberLabel = ContactsContract.CommonDataKinds.Phone.getTypeLabel(mContext.getResources(), type,
                                label).toString();
                        if (!StringUtil.isEmpty(phoneNumber)) {
                            PhoneNumberArea phoneNumberArea = PhoneNumberArea.getInstance(mContext);
//                            String area = phoneNumberArea.getArea(phoneNumber, true);
                            StringBuffer sb = new StringBuffer();
                            if (!"null".equalsIgnoreCase(numberLabel)
                                    && !StringUtil.isEmpty(numberLabel)) {
                                sb.append(numberLabel);
                            }
                            /*if (!StringUtil.isEmpty(area)) {
                                sb.append("(").append(area).append(")");
                            }*/
                            if (map_phoneNumbers == null) {
                                map_phoneNumbers = new HashMap<String, String>();
                            }
                            map_phoneNumbers.put(phoneNumber, sb.toString());
                            if (mPhoneNumbers == null) {
                                mPhoneNumbers = new ArrayList<String>();
                            }
                            mPhoneNumbers.add(phoneNumber);
                            if(foundPhone < 20 && foundPhoneType < 20){
                                bundle.putString(Contents.PHONE_TYPE_KEYS[foundPhoneType], label);
                                bundle.putString(Contents.PHONE_KEYS[foundPhone], massageContactData(phoneNumber));
                                foundPhone++;
                                foundPhoneType++;
                            }
                        }

                    } else if (ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE.equals(mime)) {
                        String email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA1));
                        int type = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                        String label = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.LABEL));
                        String emailLabel = ContactsContract.CommonDataKinds.Email.getTypeLabel(mContext.getResources(), type, label).toString();
                        if (!StringUtil.isEmpty(email)) {
                            if (map_emails == null) {
                                map_emails = new HashMap<String, String>();
                            }
                            if(foundEmailType < 20 && foundEmail < 20){
                                bundle.putString(Contents.PHONE_TYPE_KEYS[foundEmailType], emailLabel);
                                bundle.putString(Contents.EMAIL_KEYS[foundEmail], massageContactData(email));
                                map_emails.put(email, emailLabel);
                                foundEmail++;
                                foundEmailType++;
                            }

                        }
                    } else if (ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE.equals(mime)) {
                        String website = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
                        if (!StringUtil.isEmpty(website)) {
                            if (array_websites == null) {
                                array_websites = new ArrayList<String>();
                            }
                            array_websites.add(website);
                            bundle.putString(Contents.URL_KEY, website);
                        }
                    } else if (ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE.equals(mime)) {
                        String nickName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME));
                        if (!StringUtil.isEmpty(nickName)) {
                            if (array_nickName == null) {
                                array_nickName = new ArrayList<String>();
                            }
                            array_nickName.add(nickName);
                        }

                    } else if (ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE.equals(mime)) {
                        String im = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA1));
                        if (!StringUtil.isEmpty(im)) {
                            int protocol = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));
                            String label = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.LABEL));
                            String imLabel = ContactsContract.CommonDataKinds.Im.getProtocolLabel(mContext.getResources(), protocol, label).toString();
                            if (map_iMs == null) {
                                map_iMs = new HashMap<String, String>();
                            }
                            map_iMs.put(im, imLabel);
                        }
                    } else if (ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE.equals(mime)) {

                        String address = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
                        int type = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
                        String label = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.LABEL));
                        String postalLabel = ContactsContract.CommonDataKinds.StructuredPostal.getTypeLabel(mContext.getResources(), type, label).toString();
                        if (!StringUtil.isEmpty(address)) {
                            if (map_address == null) {
                                map_address = new HashMap<String, String>();
                            }
                            bundle.putString(ContactsContract.Intents.Insert.POSTAL, massageContactData(address));
                            map_address.put(address, postalLabel);
                        }

                    } else if (ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE.equals(mime)) {
                        String companyString = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
                        String positionString = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));// item.getPrimaryData();
                        if (!StringUtil.isEmpty(companyString)) {
                            if (companys == null) {
                                companys = new ArrayList<String>();
                            }
                            companys.add(companyString);
                            bundle.putString(ContactsContract.Intents.Insert.COMPANY, companyString);
                            bundle.putString(ContactsContract.Intents.Insert.JOB_TITLE, positionString);
                        }

                        if (!StringUtil.isEmpty(positionString)) {
                            if (positions == null) {
                                positions = new ArrayList<String>();
                            }
                            positions.add(positionString);
                        }

                    } else if (ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE.equals(mime)) {
                        String note = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                        if (!StringUtil.isEmpty(note)) {
                            if (array_notes == null) {
                                array_notes = new ArrayList<String>();
                            }
                            array_notes.add(note);
                        }
                    } else if (ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE.equals(mime)) {
                        mName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
                        if (!StringUtil.isEmpty(mName)) {
                            Log.d("same_contact", "name " + mName);
                            bundle.putString(ContactsContract.Intents.Insert.NAME, massageContactData(mName));
                        } else {
                            bundle.putString(ContactsContract.Intents.Insert.NAME, massageContactData("无名称"));
                        }
                    } else if (Constants.WX_CHAT.equals(mime)) {
                        String wx_tag = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DATA2));
                        String wx_type = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DATA3));
                        if ("微信".equals(wx_tag) && ("聊天".equals(wx_type) || ("发送消息").equals(wx_type))) {
                            mWxChatId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID));
                        }
                    } else if (Constants.FRIEND_CRICLE.equals(mime)) {
                        String wx_tag = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DATA2));
                        String wx_type = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DATA3));
                        if ("微信".equals(wx_tag) && ("朋友圈".equals(wx_type) || "查看朋友圈".equals(wx_type))) {
                            mWxFriendId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID));
                        }
                    } else if (ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE.equals(mime)) {
                        long rightId = -1;
                        rightId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
                        if (rightId != -1 && rightId == rowId) {
                            String groupId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID));
                            final HashMap<String, ContactsDBReader.GroupInfo> mGroupList = ContactsDBReader.mGroupList;
                            if (isInitGroup()) {
                                ContactsDBReader.GroupInfo group = mGroupList.get(groupId);
                                if (group != null) {
                                    String groupName = group.mGroupTitle;
                                    if (!StringUtil.isEmpty(groupName)) {
                                        if (groupString == null) {
                                            groupString = new StringBuilder();
                                        }
                                        groupString.append(groupName);
                                        groupString.append(",");
                                    }
                                } else {
                                    groupString = new StringBuilder();
                                    groupString.append(mContext.getResources().getString(R.string.non_group));
                                }
                                if ((groupString != null)
                                        && (!(groupString.toString().equals(mContext.getResources().getString(
                                        R.string.non_group))))) {
                                    groupString.deleteCharAt(groupString.length() - 1);
                                }

                            } else {

                            }
                        }
                    }
                    isTrue = cursor.moveToNext();
                }
                if (map_address != null && map_address.size() > 0) {
                    info.setAddresses(map_address);
                }
                if (map_phoneNumbers != null && map_phoneNumbers.size() > 0) {
                    info.setPhoneNumbers(map_phoneNumbers);
                }
                if (map_emails != null && map_emails.size() > 0) {
                    info.setEmails(map_emails);
                }
                if (map_iMs != null && map_iMs.size() > 0) {
                    info.setiMs(map_iMs);
                }
                if (companys != null && companys.size() > 0) {
                    info.setCompanys(companys);
                }
                if (positions != null && positions.size() > 0) {
                    info.setPositions(positions);
                }
                if (array_websites != null && array_websites.size() > 0) {
                    info.setWebsites(array_websites);
                }
                if (array_notes != null && array_notes.size() > 0) {
                    info.setNotes(array_notes);
                }
                if (array_nickName != null && array_nickName.size() > 0) {
                    info.setNicknames(array_nickName);
                }
                if (!StringUtil.isEmpty(mName)) {
                    info.setName(mName);
                }
                if (mWxFriendId != -1) {
                    info.setWxFriendId(mWxFriendId);
                }
                if (mWxChatId != -1) {
                    info.setWxChatId(mWxChatId);
                }
                if (rowId != -1) {
                    mRowPhoneLookUpUri = getRowLookUpUri(rowId);
                }
                if (mRowPhoneLookUpUri != null) {
                    String ring = getRing(mRowPhoneLookUpUri, contactId);
                    if (!StringUtil.isEmpty(ring)) {
                        info.setRingtongName(ring);
                    }
                    info.setRowLookupUri(mRowPhoneLookUpUri);
                }

                if (groupString != null && groupString.length() > 0) {
                    String groupName = groupString.toString();
                    if (!StringUtil.isEmpty(groupName)) {
                        info.setGroupName(groupName);
                    }
                }
                if (mPhoneNumbers != null && mPhoneNumbers.size() > 0) {
                    info.setArrayphoneNumbers(mPhoneNumbers);
                    info.setInBlackList(ContactsDBReader.isInBlackList(mContext, mPhoneNumbers));
                } else {
                    info.setInBlackList(false);
                }

                if (bundle != null && bundle.size() > 0) {
                    mDataIntent.putExtra(Intents.Encode.TYPE, Contents.Type.CONTACT);
                    mDataIntent.putExtra(Intents.Encode.DATA, bundle);
                    if (!StringUtil.isEmpty(mName)) {
                        mDataIntent.putExtra("name", mName);
                    }
                    mDataIntent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString());
//                    mDataIntent.putExtra(EncodeActivity.USE_VCARD_KEY, false);//need return to the original
                    mDataIntent.putExtra("USE_VCARD", false);
                    info.setIntent(mDataIntent);
                }
                Bitmap bitmap = ContactsDBReader.getPhotoByContactId(mContext, contactId);
                info.setPhoto(bitmap);
                Log.d("same_contact", "_______________");
                return info;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }


        return null;
    }

    public Map<Long, ArrayList<String>> getAllNumbers(long[] contactId, RoundProgressBar progressBar){
        Map<Long, ArrayList<String>> result = new HashMap<Long, ArrayList<String>>();
        int j = 0;
        for (long id : contactId){
            Log.d("same_contact", "_____________");
            progressBar.setProgress(j++);
            Uri methodUri = getMethodUri(getContactUri(id));
            Cursor cursor = null;
            try {
                cursor = mContext.getContentResolver().query(methodUri,
                        ContactsDBReader.DATA_PROJECTION, null, null, null);
                if (cursor != null && cursor.getCount() > 0) {
                    boolean isTrue = cursor.moveToFirst();
                    ArrayList<String> phones = new ArrayList<String>();
                    while (isTrue){
                        String mime = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
                        if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(mime)) {
                            final String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            if(phoneNumber != null && phoneNumber.length() > 0){
                                phones.add(phoneNumber);
                                Log.d("same_contact", "phoneNumber " + phoneNumber);
                            }
                        }
                        isTrue = cursor.moveToNext();
                    }
                    if(phones != null && phones.size() > 1){
                        result.put(id, phones);
                    }
                }

            }finally {
                if(cursor != null){
                    cursor.close();
                }
            }
            Log.d("same_contact", "_____________");
        }

        return result;
    }

    private boolean isInitGroup() {
        if (ContactsDBReader.mGroupList == null) {
            ContactsDBReader.getGroupHash(mContext.getContentResolver());
        }
        return ContactsDBReader.mGroupList != null;
    }


    private String getRing(Uri rowLookUpUri, long id) {
        String ringtone;
        Uri contactUri = getContactUri(id);
        if (contactUri == null) {
            return null;
        }
        Cursor c = mContext.getContentResolver().query(rowLookUpUri, new String[]{
                ContactsContract.Contacts.CUSTOM_RINGTONE, ContactsContract.Contacts.SEND_TO_VOICEMAIL}, null,
                null, null);
        try {
            if (!c.moveToFirst()) {
                return null;
            }

            ringtone = c.getString(0);
            if (ringtone == null) {
                ringtone = mContext.getResources().getString(R.string.moren);
                return ringtone;
            }
            Uri ringtoneUri = Uri.parse(ringtone);
            Ringtone ring = RingtoneManager.getRingtone(mContext, ringtoneUri);
            if (ring != null) {
                ringtone = ring.getTitle(mContext);
            }
        } finally {
            c.close();
        }
        return ringtone;
    }

    private Uri getContactUri(long id) {
        return ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
    }

    private Uri getMethodUri(Uri contactUri) {
        return Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
    }

    private long getRowId(long id) {
        return ContactsUtils.queryForRawContactId(mContext.getContentResolver(), id);
    }

    private Uri getRowUri(long rowId) {
        Uri rowContactUri = null;
        rowContactUri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, rowId);
        return rowContactUri;
    }

    private Uri getRowLookUpUri(long rowId) {
        return ContactsContract.RawContacts.getContactLookupUri(mContext.getContentResolver(), getRowUri(rowId));
    }

    private static String massageContactData(String data) {
        // For now -- make sure we don't put newlines in shared contact data. It messes up
        // any known encoding of contact data. Replace with space.
        if (data.indexOf('\n') >= 0) {
            data = data.replace("\n", " ");
        }
        if (data.indexOf('\r') >= 0) {
            data = data.replace("\r", " ");
        }
        return data;
    }

}
